package Game;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Stack;

//TODO: Scala med delta.
//TODO: Attack spawn

public class WaveHandler {
	
	private Wave currentWave;
	private Stack<Wave> waves;
	private ArrayList<Enemy> onTheField;
	private ArrayList<Tower> towers;
	private int SPAWNTIME = 500;
	private int nextSpawn;
	private int KILLS;
	private int LEAKED_ENEMIES;
	
	public WaveHandler(Path path){
		currentWave = null;
		waves = new Stack<Wave>();
		onTheField = new ArrayList<Enemy>();
		towers = new ArrayList<Tower>();
		nextSpawn = 0;
	}
	
	public int getLeakedEnemies() { return LEAKED_ENEMIES; }
	public int getKills() { return KILLS;}
	
	public void addWave(Wave wave){
		waves.add(wave);
	}
	
	public boolean hasNextWave(){
		return !(waves.isEmpty());
	}
	
	public void nextWave(){
		currentWave = waves.pop();
		KILLS = 0;
	}
	
	/**
	 * Update the wave of units. Move them etc.
	 */
	public void updateWave(int delta){
		if(currentWave.hasNextSpawn() && nextSpawn <= 0){
			onTheField.add(currentWave.nextSpawn());
			nextSpawn = SPAWNTIME; // TODO: SHOULD PROBABLY DEPEND ON WAVE TYPE
			System.out.println("New spawn!");
		}
		Iterator<Enemy> it = onTheField.iterator();
		while(it.hasNext()){
			Enemy enemy = it.next();
			if(enemy.isDead()){
				it.remove();
				KILLS++;
			} else {
				if(!enemy.move(delta)){
					it.remove();
					LEAKED_ENEMIES++;
				}
			}
		}		
		
		nextSpawn--;
	}
	
	public void attackWave(ArrayList<Tower> towers, int delta)
	{
		this.towers = towers;
		for(Tower tower : towers){
			Iterator<Enemy> it = onTheField.iterator();
			while(it.hasNext()){
				Enemy enemy = it.next();
				if(tower.isEnemyInRange(enemy)){
					tower.attack(enemy, delta);
				}
			}
		}
	}
	
	/**
	 * Returns the current wave
	 * @return the curent wave
	 */
	public Wave getCurrentWave()
	{
		return currentWave;
	}
	
	
	/**
	 * Draw all units currently on the field.
	 */
	public void drawWave(){
		for(Enemy enemy : onTheField){
			enemy.draw();
		}
	}
	
	/**
	 * Returns an array of all the enemies currently
	 * in the field
	 * @return an ArrayList of enemies currently on the field.
	 */
	public ArrayList<Enemy> enemies(){
		return onTheField;
	}

}
